﻿using System;
using System.Collections;
using System.Collections.Generic;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;

public class HeatMeshVisual : MonoBehaviour
{
    Grid g;
    [SerializeField] Mesh mesh;
    bool canUpdateHeatMap;

    private void Awake()
    {
        mesh = new Mesh();
        GetComponent<MeshFilter>().mesh = mesh;
    }

    //public void SetGird(Grid cur)
    //{
    //    g = cur;
    //    UpdateHeatMap();

    //    g.onGridValueChange+= HeatMapChange;
    //}

    //private void HeatMapChange(object sender, Grid.OnGridValueChangeEventArgs e)
    //{
    //    canUpdateHeatMap = true;
    //}

    //private void LateUpdate()
    //{
    //    if (canUpdateHeatMap)
    //    {
    //        canUpdateHeatMap =false;
    //        UpdateHeatMap();
    //    }
    //}


    //private void UpdateHeatMap()
    //{
    //    //创建一个多个正方形
    //    CreateSquare(g.GetHeight() * g.GetWidth(), out Vector3[] vertices, out Vector2[] uv, out int[] triangles);

    //    for (int i = 0; i < g.GetWidth(); i++)
    //    {
    //        for (int j = 0; j < g.GetHeight(); j++)
    //        {
    //            int index = i * g.GetHeight() + j;

    //            int gridValue = g.GetValue(i, j);
    //            float rate = (float)gridValue / g.GetHeatMapMax();
    //            Vector2 newUv = new Vector2(rate, 0);

    //            //创建热力图
    //            SetSquareMesh(vertices, uv, triangles, index, g.GetWorldPosition(i, j), g.GetCellSize(), newUv, newUv);
    //        }
    //    }

    //    mesh.vertices = vertices;
    //    mesh.uv = uv;
    //    mesh.triangles = triangles;
    //}


    private void CreateSquare(int count,out Vector3[] vertices, out Vector2[] uv, out int[] triangles)
    { 
        //一个正方形 4个顶点，4个uv，6个索引
        vertices = new Vector3[4*count];
        uv = new Vector2[4*count];
        triangles = new int[6*count];
    }


    private void SetSquareMesh(Vector3[] vertices, Vector2[] uv, int[] triangles, int index,Vector3 pos,float baseSize,Vector2 uv00,Vector2 uv11)
    {
        int index0 = 4 * index;
        int index1 = index0;
        int index2 = index0 + 1;
        int index3 = index0 + 2;
        int index4 = index0 + 3;

        //顶点信息
        vertices[index1] = pos;
        vertices[index2] = pos + new Vector3(0, baseSize, 0);
        vertices[index3] = pos + new Vector3(baseSize, baseSize, 0);
        vertices[index4] = pos + new Vector3(baseSize, 0, 0);

        //索引
        int tIndex = 6 * index;
        triangles[tIndex + 0] = index1;
        triangles[tIndex + 1] = index2;
        triangles[tIndex + 2] = index3;

        triangles[tIndex + 3] = index1;
        triangles[tIndex + 4] = index3;
        triangles[tIndex + 5] = index4;

        //uv
        uv[index1] = new Vector2(uv00.x, uv00.y);      
        uv[index2] = new Vector2(uv00.x, uv11.y);
        uv[index3] = new Vector2(uv11.x, uv11.y);
        uv[index4] = new Vector2(uv11.x, uv00.y);
    }

}
